//
//  AudioVideoFileCell.m
//  TrainTree
//
//  Created by wanghui on 2017/9/17.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//

#import "AudioVideoFileCell.h"
#import "ZZCircleProgress.h"
@interface AudioVideoFileCell()
{
    NSURLSessionDownloadTask *_downloadTask;
    BOOL _downloadStatus;// 下载状态，YES下载中，NO暂停下载
    BOOL _onceToken;// 第一次点击下载
}
@property (nonatomic, assign) NSInteger fileLength;
/** 当前下载长度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄对象 */
@property (nonatomic, strong) NSFileHandle *fileHandle;
/**文件名字*/
@property (nonatomic, copy)NSString *downLoadFileName;

@property (nonatomic, strong) AFURLSessionManager *manager;
@property (nonatomic, strong) ZZCircleProgress *circle2;
@property (weak, nonatomic) IBOutlet UIButton *fileButton;
@property (weak, nonatomic) IBOutlet UIButton *downBtn;
@end
@implementation AudioVideoFileCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.fileButton.layer.cornerRadius = 18.0f;
    self.fileButton.layer.masksToBounds = YES;
    
    self.circle2 = [[ZZCircleProgress alloc] initWithFrame:CGRectMake(0,0,40,40) pathBackColor:[UIColor clearColor] pathFillColor:[UIColor redColor] startAngle:0 strokeWidth:2];
    self.circle2.showPoint = NO;
    self.circle2.showProgressText = NO;
    self.circle2.animationModel = CircleIncreaseByProgress;
    self.circle2.progress = 0.0;
    [self.downPG addSubview:self.circle2];
    _downloadStatus = YES;
    _onceToken = YES;

}
- (IBAction)downLoadFile:(id)sender {
    // 下载self.fileUrl
    // 如果已下载，取值且预览
    NSString *fileDir = [[NSUserDefaults standardUserDefaults] objectForKey:self.toolUrl];
    if (fileDir) {
        [self.downBtn setImage:ImageNamed(@"reader") forState:UIControlStateNormal];
            // 预览
        if (_delegate && [_delegate respondsToSelector:@selector(quickLookFile:)]) {
            [_delegate quickLookFile:self.toolUrl];
        }
        return ;
    }else{
        [self.downBtn setImage:ImageNamed(@"download") forState:UIControlStateNormal];
    }

    if (_onceToken) {
            //远程地址
        NSURL *URL = [NSURL URLWithString:self.toolUrl];
            //默认配置
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

            //AFN3.0+基于封住URLSession的句柄
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
            //请求
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];

            //下载Task操作
        WeakSelf(ws);
        _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                // @property int64_t totalUnitCount;     需要下载文件的总大小
                // @property int64_t completedUnitCount; 当前已经下载的大小
                // 给Progress添加监听 KVO
            NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
                // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                    // 设置进度条的百分比
                ws.circle2.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
                if (ws.circle2.progress == 1) {
                     ws.circle2.hidden = YES;
                }
            });

        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
            return [NSURL fileURLWithPath:path];

        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                //设置下载完成操作
            ws.circle2.hidden = YES;
            [ws.fileBtn setImage:ImageNamed(@"reader") forState:UIControlStateNormal];
                // filePath就是你下载文件的位置，你可以解压，也可以直接拿来使用
            NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
            [[NSUserDefaults standardUserDefaults] setObject:imgFilePath forKey:ws.toolUrl];
                //            UIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];
                //            self.imageView.image = img;
            [ws downLoadFinishAndQuickLook];

        }];
        [_downloadTask resume];
        _onceToken = NO;
    } else {
        if (_downloadStatus) {
                // 暂停下载
            [_downloadTask suspend];
            _downloadStatus = NO;
        }else {
                // 继续下载
            [_downloadTask resume];
            _downloadStatus = YES;
        }
    }
}

- (void)configWithModel:(ToolModel *)model
{
    self.toolUrl = [NSString stringWithFormat:@"%@%@",TrainTreeFileImgURL,model.toolsUrl];
    self.fileName.text = model.toolsName;
    self.downLoadFileName = model.toolsName;
    self.firstType.text =[NSString stringWithFormat:@"%@ / ",model.moduleName];
    self.secondType.text = [NSString stringWithFormat:@"%@",model.lessonName];
        // 本地是否存在
    NSString *fileDir = [[NSUserDefaults standardUserDefaults] objectForKey:self.toolUrl];
    if (fileDir) {
        [self.downBtn setImage:ImageNamed(@"reader") forState:UIControlStateNormal];

    }else{
        [self.downBtn setImage:ImageNamed(@"download") forState:UIControlStateNormal];
    }
}

#pragma mark - 下载完提醒并且预览
- (void)downLoadFinishAndQuickLook
{
    UIAlertController *actionVc = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"%@下载完成",self.downLoadFileName] preferredStyle:UIAlertControllerStyleAlert];

    WeakSelf(ws);
    UIAlertAction *quickLook = [UIAlertAction actionWithTitle:@"预览" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ws quickLookFile];

    }];

    [actionVc addAction:quickLook];

    [[self getCurrentController] presentViewController:actionVc animated:YES completion:nil];
}
    // 拿到当前view所在的viewController
- (UIViewController *)getCurrentController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

- (void)quickLookFile
{
    if (_delegate && [_delegate respondsToSelector:@selector(quickLookFile:)]) {
        [_delegate quickLookFile:self.toolUrl];
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
